package com.woniuxy.book.interceptor;

import com.woniuxy.book.util.JWTUtil;
import com.woniuxy.book.util.RedisUtil;
import com.woniuxy.book.util.RequiredRole;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //跳过预检
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        //取出请求头中的token
        String accessToken = request.getHeader("token");
        String refreshToken = redisUtil.get(accessToken);
        //解析出当前用户角色
        Claims claims = JWTUtil.parseToken(refreshToken);
        String role = (String) claims.get("role");
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        RequiredRole annotation = method.getAnnotation(RequiredRole.class);
        if (annotation!=null) {
            String value = annotation.value();
            if (!value.equals(role)) {
                throw new Exception("权限不足");
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
